package com.dingding.gmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingding.gmall.common.utils.PageUtils;
import com.dingding.gmall.common.utils.Query;
import com.dingding.gmall.product.dao.CategoryDao;
import com.dingding.gmall.product.entity.CategoryEntity;
import com.dingding.gmall.product.service.CategoryService;
import com.dingding.gmall.product.vo.Catelog2VO;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        //2、组装父子树形结构
        //2.1找到所有一级分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> menus = categoryEntities.stream()
                //一级分类
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                //找到当前菜单的子菜单
                .peek((menu) -> menu.setChildren(getChildrens(menu, categoryEntities)))
                .sorted(Comparator.comparingInt(menu -> menu.getSort() == null ? 0 : menu.getSort()))
                .collect(Collectors.toList());
        return menus;
    }

    @Override
    public int removeMeunByIds(List<Long> asList) {
        // TODO 1、检查当前删除的菜单，是否被别的地方引用
        return baseMapper.deleteBatchIds(asList);
    }


    /**
     * 递归找到当前菜单的子菜单 => 对应map
     *
     * @param rootMenu   当前菜单
     * @param allEntites 所有菜单
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity rootMenu, List<CategoryEntity> allEntites) {
        List<CategoryEntity> children = allEntites.stream()
                //如果当前菜单的id等于它的上级i,说明属于上下级关系
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(rootMenu.getCatId()))
                .peek((menu) -> menu.setChildren(getChildrens(menu, allEntites)))
                //递归查找，子菜单为空的话，排序会报空指针
                .sorted(Comparator.comparingInt(menu -> menu.getSort() == null ? 0 : menu.getSort()))
                .collect(Collectors.toList());
        return children;
    }


    /**
     * 类似[2,25, 225]
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        //这个集合收集各个分类id
        List<Long> path = new ArrayList<>();
        findParentPath(catelogId,path);
        Collections.reverse(path);
        return path.toArray(new Long[path.size()]);
    }

    /**
     * 递归找到当前对象的父id
     * @param catelogId
     * @return
     */
    private void findParentPath(Long catelogId, List<Long> path){
        //收集当前节点id
        path.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(),path);
        }
    }


    /**
     *
     * @return
     */
    @Cacheable(key = "#root.method.name",value = {"category"})
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return list(new QueryWrapper<CategoryEntity>().eq("parent_cid",0));
    }

    /**
     * 基于Redis+Lua的分布式锁
     * 获取锁的同时设置过期时间,防止网络等原因导致锁没删除，其他请求一直获取锁，造成死锁
     * //     String lockValue = redisTemplate.opsForValue().get("lock");
     * //     if(StringUtils.equals(uuid,lockValue)){
     * //         redisTemplate.delete("lock");
     * //     }
     * 删除锁的时候，需要保证删的是自己的锁（使用Lua脚本）
     * @return
     */
    @Override
    public Map<String, List<Catelog2VO>> getCatelogJsonFromCacheWithRedisLock(){
        String uuid = UUID.randomUUID().toString();
        //如果其他线程进来无法获取锁，就会返回false
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,30, TimeUnit.SECONDS);
        if(lock) {
            System.out.println("获取分布式锁成功。。。");
            //1、加锁成功
            //2、执行 业务
            Map<String, List<Catelog2VO>> catelogJsonFromDB;
            try {
                catelogJsonFromDB = getCatelogJsonFromDB();
                String json = JSON.toJSONString(catelogJsonFromDB);
                redisTemplate.opsForValue().set("catelogJson",json, 1, TimeUnit.DAYS);
            } finally {
                //3、删除锁(获取uuid对比，对比成功删除，但期间有可能中断，不是原子操作)
                //解决方案：使用Lua脚本删除
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<>(script,Long.class), Collections.singletonList("lock"),uuid);
            }
            return catelogJsonFromDB;
        } else {
            //加锁失败，重试
            //休眠100ms
            System.out.println("获取分布式锁失败。。。等待重试");
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatelogJsonFromCacheWithRedisLock();
        }
    }

    /**
     * 基于Redisson的分布式锁
     * @return
     */
    public Map<String, List<Catelog2VO>> getCatelogJsonFromCacheWithRedissonLock(){
        RLock lock = redissonClient.getLock("catelogJson-lock");
        lock.lock();
        Map<String, List<Catelog2VO>> catelogJsonFromDB;
        try {
            catelogJsonFromDB = getCatelogJsonFromDB();
            String json = JSON.toJSONString(catelogJsonFromDB);
            redisTemplate.opsForValue().set("catelogJson",json, 1, TimeUnit.DAYS);
        } finally {
            lock.unlock();
        }
        return catelogJsonFromDB;
    }



        /**
         * 1、缓存穿透：查询DB不存在的数据 -> 空结果缓存
         * 2、缓存雪崩：大面积key失效 -> 过期时间加随机值
         * 3、缓存击穿：高并发下热点key恰好失效 -> 加锁 -> 双缓存
         * @return
         */
    @Override
    public Map<String, List<Catelog2VO>> getCatelogJsonFromCacheWithLocalLock(){
        String s = redisTemplate.opsForValue().get("catelogJson");
        if (StringUtils.isBlank(s)){
            System.out.println("缓存不命中。。。查询数据库。。。");
            synchronized (this) {
                Map<String, List<Catelog2VO>> catelogJsonFromDB = getCatelogJsonFromDB();
                String json = JSON.toJSONString(catelogJsonFromDB);
                redisTemplate.opsForValue().set("catelogJson", json, 1, TimeUnit.DAYS);
                return catelogJsonFromDB;
            }
        }
        System.out.println("缓存命中。。。直接返回");
        return JSON.parseObject(s, new TypeReference<Map<String, List<Catelog2VO>>>() {});
    }

    //查库
    @Override
    public Map<String, List<Catelog2VO>> getCatelogJsonFromDB() {
            String s = redisTemplate.opsForValue().get("catelogJson");
            if (StringUtils.isNotBlank(s)){
                return JSON.parseObject(s, new TypeReference<Map<String, List<Catelog2VO>>>() {});
            }
            System.out.println("查询了数据库......");
            /**
             * 1、将多次查库，变为一次
             */
            List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
            //1、查出所有 1 级分类
            List<CategoryEntity> level1 = getParent_cid(categoryEntityList, 0L);
            //2、封装数据
            level1.stream().collect(Collectors.toMap(k -> String.valueOf(k.getCatId()), v-> String.valueOf(v.getName())));
            //封装数据
            Map<String, List<Catelog2VO>> parentCid = level1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                //1、每一个的一级分类,查到这个一级分类的二级分类
                List<CategoryEntity> level2 = getParent_cid(categoryEntityList, v.getCatId());
                //2、封装上面的结果
                List<Catelog2VO> catelog2VOList = null;
                if (CollectionUtils.isNotEmpty(level2)) {
                    catelog2VOList = level2.stream().map(l2 -> {
                        Catelog2VO catelog2VO = new Catelog2VO(String.valueOf(v.getCatId()), null, String.valueOf(l2.getCatId()),l2.getName());
                        //1、找当前二级分类的三级分类封装成VO
                        List<CategoryEntity> level3 = getParent_cid(categoryEntityList,l2.getCatId());

                        if (CollectionUtils.isNotEmpty(level3)) {
                            List<Catelog2VO.Catelog3VO> catelog3VOList = level3.stream().map(l3 -> {
                                //2、封装成指定格式
                                return new Catelog2VO.Catelog3VO(String.valueOf(l2.getCatId()),String.valueOf(l3.getCatId()),l3.getName());
                            }).collect(Collectors.toList());
                            catelog2VO.setCatelog3List(catelog3VOList);
                        }

                        return catelog2VO;
                    }).collect(Collectors.toList());
                }
                return catelog2VOList;
            }));
            return parentCid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> list, Long parentCid) {
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        return list.stream().filter(item -> parentCid.equals(item.getParentCid())).collect(Collectors.toList());
    }
}